package com.ufo.exercise;

import java.util.Iterator;

public class RevertChain {

    public static void main(String[] args){
        RevertChain self=new RevertChain();
        Chain<Integer> chain=self.new Chain<>();
        chain.setVal(1).link(2).link(3).link(4);
        System.out.println(chain);
        System.out.println(self.revert(chain));
    }
    private <T> Chain<T> revert(Chain<T> first){
        return revert(first,first);
    }
    //就地反转链表
    private <T> Chain<T> revert(Chain<T> first, Chain<T> beforeTarget){
        if(beforeTarget!=null){
            Chain<T> target=beforeTarget.next;
            if(target!=null){
                beforeTarget.next=target.next;//取出目标
                target.next=first;//接到链表头
                return revert(target,beforeTarget);
            }
        }
        return first;
    }

     class Chain<T> implements Iterable<T>{
         T value;
         Chain<T> next;

         @Override
         public String toString() {
             String str=value.toString();
             if(next!=null){
                 str+="->"+next.toString();
             }
             return str;
         }


         public Chain<T> setVal(T value){
             this.value=value;
             return this;
         }
         public Chain<T> link(T value){
             this.next=new Chain<T>().setVal(value);
             return this.next;
         }

         @Override
         public Iterator iterator() {
             return new ChainIterator();
         }

         class ChainIterator implements Iterator<T>{

             @Override
             public boolean hasNext() {
                 return next==null;
             }

             @Override
             public T next() {
                 return next==null?null:next.value;
             }
         }
     }

}
